<?php
namespace app\user\controller;
class Alipay extends Base{
    public  $alipay_config;
   public function initialize()
    {
	   parent::initialize();
 
    }
    protected function init(){

		require_once EXTEND_PATH.'thinkpay/alipay/pagepay/service/AlipayTradeService.php';
		require_once EXTEND_PATH.'thinkpay/alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';



		$alipay_config = array (	
			//应用ID,您的APPID
			'app_id' => $this->settings['pay']['alipay_app_id'],
	
			//商户私钥
			'merchant_private_key' => $this->settings['pay']['alipay_merchant_private_key'],
			
			//异步通知地址
			'notify_url' => request()->domain().'/user/alipay/notifyUrl', 
			
			//同步跳转
			'return_url' => request()->domain().'/user/alipay/returnUrl',
	
			//编码格式
			'charset' => "UTF-8",
	
			//签名方式
			'sign_type'=>"RSA2",
	
			//支付宝网关
			'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
			
			//支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
			'alipay_public_key' => $this->settings['pay']['alipay_public_key'],
		);

	
        $this->alipay_config = $alipay_config;

		if(empty($this->settings['pay']['alipay_status'])){
                        
			return $this->error('支付宝充值未开启','user/finance/recharge');
		}
		if(empty($this->alipay_config['app_id'])){
		   return $this->error('支付宝应用appid没有配置','user/finance/recharge');
		}  
		if(empty($this->alipay_config['merchant_private_key'])){
			return $this->error('商户私钥没有配置','user/finance/recharge');
		 }  	
		 if(empty($this->alipay_config['alipay_public_key'])){
			return $this->error('支付宝公钥没有配置','user/finance/recharge');
		 }  
    }
// 处理支付
	public function pay(){
	    	$this->isLogin(); //支付必须登陆，初始化无需登陆
		   $this->init(); //初始化配置
		   $param = $this->request->param();	   
			   //验证
			   $rule =[    
				'money'=>'require|float|max:11',
					 
			   ];
			   $msg= [
				'money.require' =>'请输入充值金额',
				'money.float'   =>'请输入正确的金额格式',
				'money.max'     =>'充值金额超限',
			  ];
            $error = $this->checkSubmit($param,$rule,$msg);  //调用common 公共控制器中的 checkSubmit 方法
            if($error){
                return $this->error($error,'@user/finance/recharge');
			}  

			$money  = sprintf("%.2f",$param['money']);
			//商户订单号，商户网站订单系统中唯一订单号，必填
			$out_trade_no = get_order_no(); //创建订单号

			//订单名称，必填
			$subject = session('username').'('.$this->settings['site']['sitename'].'充值:'.$money.'元)';  
			//付款金额，必填
			$total_amount = $money; //单位元

			//商品描述，可空
			$body = '余额充值';	
		//生成支付订单
		   $data['order_no'] = $out_trade_no; //创建订单号
		   $data['amount']   = $total_amount;
		   $data['uid']      = session('uid');
		   $data['username'] = session('username');
		   $data['create_time'] = time();
		   $data['bankname'] = '支付宝PC端';


      //判断订单id 是否存在
      if(cookie('alipay_order_id')){
        $map['id'] = cookie('alipay_order_id');
        $map['amount'] = $money;
        $map['status'] = 0;
        $financeRecharge  = model('financeRecharge')->infoData($map);
        $out_trade_no = $financeRecharge['order_no'];
        if(empty($financeRecharge)){
          $financeRecharge = model('financeRecharge')->addData($data);
        
           $out_trade_no = $financeRecharge->order_no;
          cookie('alipay_order_id',$financeRecharge->id,24*3600);
        }
      }else{
        $financeRecharge = model('financeRecharge')->addData($data);
     
          $out_trade_no = $financeRecharge->order_no;
        cookie('alipay_order_id',$financeRecharge->id,24*3600);
      
      }
      

	//构造参数
	$payRequestBuilder = new \AlipayTradePagePayContentBuilder();
	$payRequestBuilder->setBody($body);
	$payRequestBuilder->setSubject($subject);
	$payRequestBuilder->setTotalAmount($total_amount);
	$payRequestBuilder->setOutTradeNo($out_trade_no);

	$aop = new \AlipayTradeService($this->alipay_config);
	

	$response = $aop->pagePay($payRequestBuilder,$this->alipay_config['return_url'],$this->alipay_config['notify_url']);

  
	}
/*
*********************************** 
* 手机支付
***********************************
*/	 
    // public function wapPay(){
    //     $this->init();
	//     $param = request()->post();

	//     if(empty($param['amount'])){
    //       $this->error('充值金额不存在');
	//     }

    //     //创建订单
    //     $data['amount']      =  addslashes($param['amount']); //充值金额
	// 	$data['username']    =  session('username'); //用户名
	// 	$data['bankname']    = '支付宝移动端';
	// 	$data['create_time'] = time();
	// 	$data['status'] = 0; 	    
	// 	//添加订单信息
	

	//    //订单信息生成
    //     $total_fee = $data['amount'];   //支付金额，以元为单位。$total_fee='100'代表100元
    //     $body      = '帐户余额充值(来自:'.session('uid').')';   //商品描述
    //     $subject   =  $data['username']."(在线充值 ".$total_fee."元)";  //商品名称，不要使用充值、支付宝等字眼，会报错。          
    //     $out_trade_no =  $data['id'];  //订单号，自己生成

    //     //初始化获取基本配置信息
    //     $alipay_config = $this->alipay_config; //获得wap配置
	// 	//构造请求的参数数组
	// 	$parameter = array(
	// 	"service"       => 'alipay.wap.create.direct.pay.by.user', //手机支付
	// 	"partner"       => $alipay_config['partner'],
	// 	"seller_id"     => $alipay_config['seller_id'],
	// 	"payment_type"	=> $alipay_config['payment_type'],
	// 	"notify_url"	=> $alipay_config['notify_url'],
	// 	"return_url"	=> $alipay_config['return_url'],
	// 	"anti_phishing_key"=>$alipay_config['anti_phishing_key'],
	// 	"exter_invoke_ip"=>$alipay_config['exter_invoke_ip'],
	// 	"out_trade_no"	=> $out_trade_no,
	// 	"subject"	=> $subject,
	// 	"total_fee"	=> $total_fee,
	// 	"show_url"	=> $show_url,
	// 	"body"	=> $body,
	// 	"_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
	// 	);

	// 	//建立请求，跳转
    //     $alipaySubmit = new \AlipaySubmit($alipay_config);
    //     $html_text = $alipaySubmit->buildRequestForm($parameter,"post", "OK");
	//     //$html_text是支付表单，这个表单是会自动跳转到支付宝支付页面
	// 	//可查看alipay_submit.class.php中buildRequestForm()方法
    //     echo $html_text;
    //     return true;
    // }

	public function returnUrl(){
		 if(!request()->isGet()){  return '非法请求';}
			$this->init();
	        $param = request()->param();
			$arr= $param;
			$alipaySevice = new \AlipayTradeService($this->alipay_config); 

	
			$result = $alipaySevice->check($arr);
	
			if($result) {//验证成功

				//商户订单号
				$order_no = htmlspecialchars($_GET['out_trade_no']);
			
				//支付宝交易号
				$trade_no = htmlspecialchars($_GET['trade_no']);
									    //判断该笔订单是否在商户网站中已经做过处理
					 $where['order_no'] = $order_no;
					 $where['status']   = 0; //等待支付
					 $financeRecharge= model('financeRecharge')->infoData($where);
				if(!empty($financeRecharge)){

				// echo "验证成功<br />支付宝交易号：".$trade_no;
			   	//更新充值记录
				                       $data['status']    = 1;
				                       $data['pay_time']  = time();
				                       $data['trade_no']  = $trade_no;
				                       $where['order_no'] = $order_no;
				                       //更新数据
				                       $res = model('financeRecharge')->editData($data,$where);
				                       if($res){
										      //加钱
											 model('user')->payin($financeRecharge['uid'],$financeRecharge['amount'],'支付宝充值',"支付宝");
											        //通知
							 $url = '<a href="'.url('user/finance/rechargerecord')."?order_no=".$financeRecharge['order_no'].'">'.$financeRecharge['order_no'].'</a>';
							 model('message')->send($financeRecharge['uid'],'支付宝充值消息','充值订单号：'.$url.'，支付宝充值成功');
				                       	    $this->success('充值成功','@user/index/index');
				                       }else{
											$this->error('充值失败','@user/finance/recharge');
										 }
				}else{
					$this->error('该订单不存在','@user/finance/recharge');
				}
			}else {
				//验证失败
				$this->error('验证失败：'.$trade_status,'@user/finance/recharge');
			}

		

	}


/*
*********************************** 
* 支付成功 异步返回，线上使用才有效果
***********************************
*/	 
	public function notifyUrl(){
		if(!request()->isPost()){  return '非法请求';}
	    $param = request()->post();
	
		//计算得出通知验证结果
		$this->init();
		
		$alipaySevice = new \AlipayTradeService($this->alipay_config); 

		// $alipaySevice->writeLog(json_encode($param));
        $result = $alipaySevice->check($_POST);
		if($result) {//验证成功

			    $out_trade_no    = addslashes($param['out_trade_no']);  //商户订单号
			    $trade_no        = addslashes($param['trade_no']);  //支付宝交易号 
				$trade_status    = addslashes($param['trade_status']); //交易状态
				$total_amount    = addslashes($param['total_amount']); //所需费用
			if($param['trade_status'] == 'TRADE_FINISHED') {
		
				//判断该笔订单是否在商户网站中已经做过处理
						
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
			}else if ($param['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
				
				//注意：
				//付款完成后，支付宝系统发送该交易状态通知

				    $where['order_no'] = $out_trade_no;  //本站订单号
					$where['status']   = 0; //等待支付
				    $financeRecharge= model('financeRecharge')->infoData($where);
				    if(!empty($financeRecharge)){
					    if($financeRecharge['status'] == 0 && $financeRecharge['amount'] == $total_amount){
	                      //更新充值记录
	                       $data['status'] = 1;
	                       $data['pay_time'] = time();
	                       $data['trade_no'] = $trade_no; //支付平台订单号
	                       $where['order_no']      = $out_trade_no; //商户订单号
	                       //更新数据
	                       $res = model('financeRecharge')->editData($data,$where);
	                       if($res){
							   //加钱
							 model('user')->payin($financeRecharge['uid'],$financeRecharge['amount'],'支付宝充值',"支付宝");
                            //通知
							 $url = '<a href="'.url('user/finance/rechargerecord')."?order_no=".$financeRecharge['order_no'].'">'.$financeRecharge['order_no'].'</a>';
							 model('message')->send($financeRecharge['uid'],'支付宝充值消息','充值订单号：'.$url.'，支付宝充值成功');
				           //付款完成后，支付宝系统发送该交易状态通知
	                       	 return "success";		//请不要修改或删除
	                       	 
	                       }
	                     
					    }
				    }


	
			}
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			exit("success");	//请不要修改或删除
		}else {
			//验证失败
			exit("fail");
		
		}

		

	}


}